package com.bankcomm.ui;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.WindowManager;
import com.bankcomm.BankcommApplication;
import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.util.DownloadThread;
import com.bankcomm.util.PreferenceHelper;
import com.rytong.tools.clienthello.ClientHello;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.ui.BaseView;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

public class BaseViewCopy extends BaseView {

	private String errorStr;
	private String errorType;
	private String errorConfirm;
	private String errorRelogin;
	private String errorCancel;
	private AlertDialog dialog;
	private LPMid mid_;
	protected ClientHello hello;
	public int mTheme = R.style.AppTheme_Default;
	private String errorCode;
	public DownloadThread downloadThread=null;

	public static BaseViewCopy instence;

	public static BaseViewCopy getInstence() {
		return instence;
	}
	
	/**
	 * 调用系统震动功能，供密码键盘点击使用
	 * @return Vibrator
	 */
	public Vibrator vibrator(){
		Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
		return vibrator ;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		/**
		 * 
		 * 换肤调用方法 attr.xml中加入所有要替换的图片的参数，如： <attr name="background"
		 * format="reference"/>
		 * 在布局xml中控件设置背景处：android:background="?attr/background" 在style中配置，皮肤样式
		 * PreferenceHelper.setTheme(BOC_SpecialShop_main_Activity.this, mTheme
		 * == R.style.AppTheme_Default ? R.style.AppTheme_Another :
		 * R.style.AppTheme_Default); reload();
		 * */
		if (savedInstanceState == null) {
			mTheme = PreferenceHelper.getTheme(this);
		} else {
			mTheme = savedInstanceState.getInt("theme");
		}
		instence = this;
		setTheme(mTheme);
		super.onCreate(savedInstanceState);
		mid_ = LPMid.getInstance();
		BankcommApplication.getInstance().addActivity(this);
		try{
			getStateOfSnapShot();
		}catch (Exception e) {
		}
//		window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
	}
	
	void getStateOfSnapShot() throws Exception{
		String flag=PackageManagerAndroid.ANDROIDDB.get("snapshot");
		if(!flag.equals("")){
		setDisSnapShot(flag);
		}
	}

	/** 集中处理异常
	 * <error string="" errorcode=""/>
	 * <error type="timeout" string="错误信息" relogin="重新登录" cancel="退出"/>
	 * **/
	public void handleException(String errMsg) {
		if (null != errMsg && errMsg.indexOf("<error") != -1) {
			String error = Utils.getXMLResponseAttribute(errMsg, "string=\"", 0, Utils.MATCH);
			// 错误信息
			errorStr = "错误信息:"+error;
			// 错误类型
			errorType = Utils.getXMLResponseAttribute(errMsg, "type=\"", 0, Utils.MATCH);
			// 错误码
			errorCode =Utils.getXMLResponseAttribute(errMsg, "errorcode=\"", 0, Utils.MATCH);
			
			// 错误信息弹出后按钮文本
			errorConfirm = Utils.getXMLResponseAttribute(errMsg, " confirm=\"", 0, Utils.MATCH);
			errorRelogin = Utils.getXMLResponseAttribute(errMsg, "relogin=\"", 0, Utils.MATCH);
			errorCancel = Utils.getXMLResponseAttribute(errMsg, "cancel=\"", 0, Utils.MATCH);
            
			errorConfirm = errorConfirm != null ? errorConfirm : getString(R.string.quit);
			errorRelogin = errorRelogin != null ? errorRelogin : getString(R.string.relogin);
			errorCancel = errorCancel != null ? errorCancel : getString(R.string.cancel);
			errorCode = errorCode != null ? "错误码:"+errorCode +"\n" : "";
			if(!errorCode.equals("")){
				errorStr=errorCode+errorStr;	
			}else{
				errorStr=error;
			}
			
			if (errorType != null) {
				if (errorType.equals("timeout")) {
					showErrorDailog("timeout");
				}
			}else{
				showErrorDailog("normal");
			}
		} else if (null != errMsg && !"".equals(errMsg)) {
			if (errMsg.contains(".NullPoi")) {
				errorStr=Utils.getConfigStringFormAsset(Utils
						.getActivity(), "httpError");
			}else{
				errorStr = errMsg;	
			}
			showErrorDailog("normal");

		} else {
			// responseCode
		}
	}

	// 弹出错误提示框
	public void showErrorDailog(String type) {
		final Builder ad = new AlertDialog.Builder(this);
		ad.setTitle(getString(R.string.alert)).setMessage(errorStr);
		if (type.equals("normal")) {
			ad.setPositiveButton(R.string.quit,
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// BaseViewCopy.this.finish();
							// android.os.Process.killProcess(android.os.Process.myPid());
							// dialog.cancel();
						}
					}
			);
		} else if (type.equals("timeout")) {
			ad.setCancelable(false);
			ad.setPositiveButton(R.string.exit, new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					exitSystem();
					dialog.cancel();
				}
			})
			.setNegativeButton(R.string.relogin,
					new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					reConnect(BaseViewCopy.this);
					dialog.cancel();
				}
			});
		}
		
		if(null != ad){
			this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ad.show();
				}
			});
		}
	}

	/**
	 * 重建加密通道
	 * @param baseViewCopy
	 */
	protected void reConnect(final BaseViewCopy baseViewCopy) {
		LPMid.getInstance().isTimeOut = true;
		LPToastUtil.isBuildChannel = false;
		mid_.waitDialog_.addFgTask(baseViewCopy, null, 0, 0, 0, new WaitDialog.Task(0) {

			String reply = null;
			@Override
			public void run(WaitDialog dlg) throws Exception {
				if(!Utils.isConnectByNet()){
					throw new Exception("网络未连接，请检查您的网络设置。");
				}
				LPToastUtil.getInstance().isBranchBank=false;
				hello = new ClientHello(BaseViewCopy.this, ConfigManager.SERVER_URI, mid_.midletVersion_, ConfigManager.CLIENT_HELLO,
						ConfigManager.CLIENT_KEY_EXCHANGE, ConfigManager.CLIENT_FACILITY_HELLO, Utils.CERTIFICATE, "&rebuild=true");
				reply = ClientHello.getText();
			}

			public void onSuccess(WaitDialog dlg) {
				if (null != reply && !"".equalsIgnoreCase(reply)) {
					if(null != mid_.um_.data){
						LPMid.getInstance().um_.data.resetLoginInfo();
					}
					Message msg = new Message();
					hanlder.sendMessage(msg);
				}
				super.onSuccess(dlg);
			}
			public void onFailure(WaitDialog dlg) {
				handleException(getErrMsg());
			}
		});
	}

	private Handler hanlder = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			BankcommApplication.getInstance().exit();
			Intent intent = new Intent();
			intent.setClass(BaseViewCopy.this, BOCMainHome.class);				
			BaseViewCopy.this.startActivity(intent);
		}
	};
	
	/**设置禁止截屏**/
	public Handler DisableSnapShotHandler=new Handler(){
		public void handleMessage(Message msg) {
			if (null != msg &&  msg.what==1000){
				String flag=(String)msg.obj;
				PackageManagerAndroid.ANDROIDDB.save("snapshot", flag);
				setDisSnapShot(flag);
				reload();
			}
		};
	};
	
	/**
	 * 退出程序
	 */
	public void exitSystem() {
		finishAppAnti();
		/**
		 * 当退出时，要结束List中的所有activity add by chengli
		 * */
		BankcommApplication.getInstance().exit();
		// 停止程序开启的服务，保证程序退出后不会常驻内存
		Intent intent = new Intent();
		intent.setAction(getClass().getPackage().getName());
		stopService(intent);
		/**
		 * 一般是采用finish方法,但是在转换wifi和wap连接的时候会出现系统提示连接长时间死亡的情况.
		 */
		System.exit(0);
	}
	
	/**
	 * 退出系统时确认对话框
	 */
	public void exitWithConfirm() {
		new AlertDialog.Builder(this).setTitle(R.string.quit_prompt).setMessage(R.string.quit_confirm)
			.setPositiveButton(R.string.quit,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						exitSystem();
					}
				})
			.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub

					}
			}).show();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (mTheme != PreferenceHelper.getTheme(this)) {
			reload();
		}
		try {
			getStateOfSnapShot();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("theme", mTheme);
	}

	protected void reload() {
		Intent intent = getIntent();
		//overridePendingTransition(0, 0);
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		finish();
		//overridePendingTransition(0, 0);
		startActivity(intent);
	}

	public void setDisSnapShot(String flag){
		if(flag.equals("yes")){
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
		}else{
	    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
		}
	}
}
